// 创建用户相关的小仓库
import { defineStore } from 'pinia'
// 引入接口
import { reqLogin, reqUserAdd, reqUserAll, reqUserById, reqUserDelete, reqUserList, reqUserUpdate } from '@/api/user'
// 引入数据类型
import type { loginFormData, loginResponseData, userAllResponseData, userInfoData, userListFormData, userListResponseData } from '@/api/user/type'
// 引入state返回对象类型
import type { UserState } from './types/type'
// 创建用户小仓库
let useUserStore = defineStore("User",{
    // 这里使用选择式Api写法
    // 存储数据位置
    // 指定state函数返回值类型为UserState
    state:() : UserState=>{
        return{
            token:localStorage.getItem('VUE3-TOKEN')||"",// 用户唯一标识token
            user:JSON.parse(localStorage.getItem("B0445-STU-USER")|| "{}"),
            users:[]
        }
    },
    // 异步|逻辑
    actions:{
        // 用户登录方法，因为async函数会返回一个promis对象，所以可以通知组件请求是否成功
        async userLogin(data:loginFormData){
            // 登录请求
            let result:loginResponseData = await reqLogin(data);
            // 登录成功：获取token，进行存储之后再任何请求时都在headers中携带
            // 登录失败：获取失败错误信息
            if(result.status == 0){
                // pinia仓库存储token
                // 由于pinia/vuex存储数据其实利用的是js对象，所以刷新后会恢复到默认值
                // 断言数据式字符串类型
                this.token = (result.data?.token as string)
                // @ts-ignore
                this.user = result.data?.user 
                // 本地持久存储化
                localStorage.setItem("VUE3-TOKEN",this.token)
                localStorage.setItem('B0445-STU-USER', (JSON.stringify(this.user) as string))
                // 当前async函数返回一个成功的promise
                return 'OK'
            }else{
                return Promise.reject(new Error(result.msg))
            }
        },
        removeUser(){
            this.token=""
            this.user = null;
            localStorage.removeItem('VUE3-TOKEN')
            localStorage.removeItem("B0445-STU-USER")
        },
        // 获取所有用户列表
        async getUserAll(){
            let result:userAllResponseData = await reqUserAll()
            if(result.status == 0){
                this.users = (result.data as userInfoData[])
                return 'OK'
            }else{
                return Promise.reject(new Error(result.msg))
            }
        },
        // 分页获取用户列表
        async getUserList(data:userListFormData){
            let result:userListResponseData = await reqUserList(data)
            if(result.status == 0){
                this.users = (result.data?.data as userInfoData[])
                return result.data
            }else{
                return Promise.reject(new Error(result.msg))
            }
        },
        // 添加用户
        async addUser(data:userInfoData){
            let result:loginResponseData = await reqUserAdd(data);
            if(result.status == 0){
                this.getUserAll()
                return "ok"
            }else{
                return Promise.reject(new Error(result.msg))
            }
        },
        // 根据id查询用户
        async getUserById(_id:string){
            let result:loginResponseData = await reqUserById(_id);
            if(result.status == 0){
                return result.data
            }else{
                return Promise.reject(new Error(result.msg))
            }
        },
        // 更新用户
        async updateUser(data:userInfoData){
            let result:loginResponseData = await reqUserUpdate(data);
            if(result.status == 0){
                this.getUserAll()
                return "ok"
            }else{
                return Promise.reject(new Error(result.msg))
            }
        },
        // 删除用户
        async deleteUser(userId:string){
            let result:loginResponseData = await reqUserDelete(userId);
            if(result.status == 0){
                this.getUserAll()
                return "ok"
            }else{
                return Promise.reject(new Error(result.msg))
            }
        }
    },
    // 计算属性
    getters:{

    }
})
export default useUserStore